<?php
namespace app\dao;

use app\dao\BaseDAO;
use Yii;
use app\enum\EnumOther;
use yii\db\Query;

class SaleOutDetailDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2017-02-07
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'saleout_detail';
		$this->_pKey ='saleout_det_id';
	}

	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%saleout_detail}}';
	}
	
	/**
	 * @desc 根据id 获取销售出库单明细
	 * @param $id 出库单id
	 * @author liaojianwen
	 * @date 2017-02-08
	 */
	public function getSaleOutDet($id)
	{
		$selects = "saleout_det_id,d.saleout_id,d.product_id,d.quantity,d.remark,p.product_name,product_sn,s.warehouse_id,return_quantity,minus_quantity,base_price,
				d.quantity_unit,d.price,d.amount,d.discount,base_quantity,base_unit,u.unit_name base_name,second_quantity,second_unit,second_relation,p.unit_content";
		$conditions ="d.saleout_id = :id and d.delete_flag = :flag";
		$params = [
				':id'=>$id,
				':flag'=>EnumOther::NO_DELETE,
		];
		$query = new Query();
		$result = $query->select($selects)
		->from("$this->_table d")
		->leftJoin("product p",'d.product_id = p.product_id')
		->leftJoin("unit u","u.unit_id = d.base_unit")
		->leftJoin("saleout s","s.saleout_id = d.saleout_id")
		->where($conditions,$params)
		->all();
		foreach ($result as &$res){
			$res_units = ProductUnitDAO::getInstance()->getUnits($res['product_id'] );
			$res['product_unit'] = $res_units;
			$res_quantity = StockPileDAO::getInstance()->findByAttributes('quantity','product_id = :pid and warehouse_id =:wid',[':pid'=>$res['product_id'],':wid'=>$res['warehouse_id']]);
			$res['product_quantity'] = isset($res_quantity['quantity']) ? $res_quantity['quantity']:0;
		}
		return $result;
	
	}
	
	/**
	 * @desc 确认采购订单明细已收到数量，确认是否完成
	 * @param $proid 采购订单id
	 * @param  [ 
				  'salereturn_no' => string 'XSTH-20170425093016' (length=19)
				  'product_id' => string '7' (length=1)
				  'quantity' => string '10.00' (length=5)
				  'salereturn_type' => string '15' (length=2)
				  'salereturn_det_id' => string '80' (length=2)
				  'warehouse_id' => string '1' (length=1)
				  'salereturn_date' => string '1493078400' (length=10)
				  'quantity_unit' => string '2' (length=1)
				  'base_quantity' => string '10.00' (length=5)
				  'base_unit' => string '2' (length=1)
				  'customer_id' => string '51' (length=2)
				  'saleout_id' => string '35' (length=2)
				  'saleout_det_id' => string '0' (length=1)' (length=2)
		  ]
	 * @author liaojianwen
	 * @date 2017-04-26
	 */
	public function updateFinish($proid, $det)
	{
		$pro_det = $this->findByAttributes ( "minus_quantity,return_quantity,base_quantity,finish_flag", "saleout_det_id =:detid", [
				':detid' => $det ['saleout_det_id']
		] );
		$total_quantity = $pro_det ['return_quantity'] + $det ['base_quantity'];
		if ($total_quantity > $pro_det ['base_quantity']) {
			//现在的值加上原来单据上的超过了未收的数量
			$result ['Ack'] = 'error';
			$result ['msg'] = 'total quantity is lt return_quantity';
			return $result;
		} else if ($total_quantity == $pro_det ['base_quantity']) {
			//现在数量加上单据上的数量 刚好等于未收数量//标记完成
			$detail_flag = SaleOutDetailDAO::getInstance ()->iupdate ( [
					'finish_flag' => EnumOther::FINISHED
			], "saleout_det_id=:pid", [
					':pid' => $det ['saleout_det_id']
			] );
			if (! $detail_flag) {
				$result ['Ack'] = 'error';
				$result ['msg'] = 'update detail finish_flag fail';
				return $result;
			}
		}
		$condition = "saleout_det_id =:detid";
		$params = [
				':detid' => $det ['saleout_det_id']
		];
		$received_quantity = $this->updateAllCounters ( [
				"return_quantity" => $det ['base_quantity'],
				"minus_quantity"=> -$det['base_quantity'],//未退数量变更为原来单据数量- 已收数量
		], $condition, $params );
		if (! $received_quantity) {
			$result ['Ack'] = 'error';
			$result ['msg'] = 'update return quantity fail';
			return $result;
		}
	
		//查找是否还有未完成的明细，如果有就不用给head 更新finish_flag,如果没有就给head 的finish_flag 打上完成
		$exit_unfinish = SaleOutDetailDAO::getInstance ()->findByAttributes ( "saleout_det_id", "saleout_id=:pid and finish_flag=:flag and delete_flag = :dflag", [
				':pid' => $proid,
				':flag' => EnumOther::NO_FINISHED,
				':dflag' => EnumOther::NO_DELETE,
		] );
		if (!$exit_unfinish) {
			$head_flag = SaleOutDAO::getInstance ()->iupdate ( [
					'finish_flag' => EnumOther::FINISHED
			], "saleout_id=:pid", [
					':pid' => $proid
			] );
			if(empty($head_flag)) {
				$result ['Ack'] = 'error';
				$result ['msg'] = 'update head finish_flag fail';
				return $result;
			}
		}
		return [
				'Ack' => 'success'
		];
	}
}